﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using TeaLightV5.Foundation.BL;
using TeaLightV5.Foundation.Sal.Interfaces;

namespace TeaLightV5.Foundation.Dal
{
    public class Repository
    {
        private static readonly ICollection<Type> _Repositories = new Collection<Type>();

        private static ICollection<Type> Repositories
        {
            get
            {
                return _Repositories;
            }
        }

        public static void Register<T>()
            where T : IRepositoryBase
        {
            _Repositories.Add(typeof(T));
        }

        public static T Create<T>()
            where T : IRepositoryBase
        {
            return Activator.CreateInstance<T>();
        }

        public static IRepositoryBase<T, TKey> GetRepository<T, TKey>()
            where T : IEntity<TKey>, new()
            
        {
            Type repositoryType = typeof(IRepositoryBase<T, TKey>);
            foreach (var type in Repositories)
            {
                bool canCreate;

                // todo
                //#if NETFX_CORE
                canCreate = repositoryType.IsAssignableFrom(type);

                //#else
                //                canCreate = repositoryType.IsAssignableFrom(type);
                //#endif
                if (canCreate)
                {
                    return Activator.CreateInstance(type) as IRepositoryBase<T, TKey>;
                }
            }
            return new RepositoryBase<T, TKey>();
        }
    }
}